﻿package game.network.api {
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import game.objects.GameObject;
	import game.network.INetwork;
	import game.Config;
	import game.objects.UserApiObject;
	import game.debug.Debug;
	
	public class vkDesktop extends GameObject implements INetwork {
		
		public static const FIELDS:String				= "uid,first_name,last_name,screen_name,photo_medium,sex";
		
		public static const GET_PROFILES:String			= "users.get";
		public static const GET_FRIENDS:String			= "friends.getAppUsers";
		
		public function getProfiles(uids:String, callBack:Function):void {
			send(vkDesktop.GET_PROFILES, {uids: uids, fields: vkDesktop.FIELDS}, function (arr:Array) { 
				 var v:Vector.<UserApiObject> = new Vector.<UserApiObject>;
				 for each (var obj:Object in arr) { 
				 	v.push( new UserApiObject ( obj.uid, obj.first_name, obj.last_name, obj.screen_name, obj.photo_medium, obj.sex, 'http://vk.com/id'+String(obj.uid) ) );
				 }
				 callBack(v);
			});
		}
		
		public function getFriends(callBack:Function):void {
			send(vkDesktop.GET_FRIENDS, {}, function (arr:Array) {
				if (arr.length>0)
					getProfiles(arr.join(','), callBack);
				else
					callBack(new Vector.<UserApiObject>);
			});
		}
		
		private function send(method:String, data:Object = null, callBack:Function = null):void {
			var vars:URLVariables = new URLVariables;
			for (var i in data) {
				vars[i] = data[i];
			}
			vars.access_token = config.me.access_token;
			
			var req:URLRequest	= new URLRequest (Config.VK_API+method);
			req.method			= URLRequestMethod.POST;
			req.data = vars;
			
			var loader:URLLoader = new URLLoader;
			loader.addEventListener(IOErrorEvent.IO_ERROR, function (event:IOErrorEvent) { errorCallback({error_msg: event.text}); });
			loader.addEventListener(Event.COMPLETE, function (event:Event) { var result:Object = JSON.parse(loader.data); if (result.error) { errorCallback(result.error); } else callBack(result.response); });
			loader.load( req );
		}
		
		private function errorCallback(error:Object):void {
			debug ( error.error_msg, Debug.API );
		}
	}
}